<template>
   <div ref="esignBox" class="esign-box" @mouseleave="getBase64(true)">
     <div  v-show="strings.isNotBlank(propTitle)" style="text-align: center;    height: 15px;">
       {{propTitle}}
     </div>
     <div  >
       <vue-esign  ref="esign" class="esign" :width="propWidth" :height="propHeight" :isCrop="isCrop" :lineWidth="lineWidth" :lineColor="lineColor" :bgColor.sync="bgColor"
        :disabled ="propDisabled"
       />
     </div>
     <div class="btns">
       <el-button-group  >

       <!--  <el-button type="warning" size="mini"  @click="clickFun(2)">撤销</el-button>-->
         <el-button type="warning" :size="propBtnSize"  @click="clickFun(3)" :disabled="propDisabled" style="margin-right: 3px" title="清空当前签名" v-show="isShowOp">重写</el-button>
         <el-button type="primary" :size="propBtnSize"  @click="clickFun(1)" :disabled="propDisabled" v-if="propShowSave" style="margin-right: 3px"  v-show="isShowOp" title="系统签名与用户绑定">更新系统签名</el-button>
         <el-button type="primary" :size="propBtnSize"  @click="clickFun(1)" :disabled="propDisabled" v-if="propShowSaveUser" style="margin-right: 3px"  v-show="isShowOp" title="保存当前签名">保存</el-button>
         <el-button type="" :size="propBtnSize"  @click="clickFun(4)" v-show="propShowClose">关闭</el-button>
       </el-button-group>
     </div>
   </div>
</template>

<script>
/*eslint-disable*/
/*条形码、二维码*/
import vueEsign from 'vue-esign'

export default {
  name: 'FortenEsign',
  title: '电子签名',
  props: {
    fileSavePath: {type: String, default: 'tmp'},//文件保存路径,从res:real-path 开始
    fileRefTable: {String,default:null},//文件关联表
    fileRefId: {String,default:null}, //文件关联id
    fileRefIdOnlyOne: {String,default:null}, //1:fileRefId 存进文件表时，只保留一个，会先将之前的删除掉
    propBtnSize: {String,default:'mini'}, //底部操作栏按钮大小，medium small mini
    propShowSave: {Boolean,default:false}, //是否显示保存系统签名按钮 false:隐藏
    propShowSaveUser: {Boolean,default:false}, //是否显示保存用户签名按钮 false:隐藏
    propShowClose: {Boolean,default:false}, //是否显示关闭按钮 true:显示，当签名组件嵌入到弹框，关闭后将回调父组件  sign-close 事件
    propWidth: {Number,default:300}, //宽度
    propHeight: {Number,default:100}, //高度,
    propTitle: {String,default:null},//头部标题
    propDisabled: {Boolean,default:false}, //是否禁用
    propAutoSave: {Boolean,default:false}, //自动保存，鼠标移除后
    propShowSuccess: {Boolean, default: false} //是否提示保存成功，默认不提示，因为还要回传给父组件，父组件有提示，避免重复提示
  },
  components: {vueEsign},
  data() {
    return  {
      lineWidth: 6,
      lineColor: '#000000',
      bgColor: '',
      resultImg: '',
      isCrop: false,
      esign: null,
      base64: null,
      base64Old: null,
      baseApi: location.origin+'/api',
      isShowOp: true,
      filePath: null,
      unNeedSave: 'unNeed'
    }
  },

  methods: {
    //点击事件
    clickFun(type){
      switch(type){
        case 1: //保存
         this.upload()
          break;
        case 2: //撤销
          break;
        case 3: //重写
          this.setData()
          break;
        case 4: //关闭窗口
          this.$emit('sign-close')
          break;
      }
    },
    //上传
    async upload(isMouseleave){
      let base64 = await this.getBase64()
      if (this.unNeedSave == base64) { //因为未修改，不需要保存
        return
      }
      if (base64 == null) {
        if (isMouseleave != true) this.utilMessage.warning('当前无签名或者未更新签名，请签名后再保存')
        return
      }
      this.base64Old = base64
      this.base64 = base64
      this.utilVue.loadShow(true)
      let postData = {
        base64Str: base64,
        fileSavePath: this.fileSavePath,
        fileRefId: this.fileRefId,
        fileRefTable: this.fileRefTable,
        fileRefIdOnlyOne: this.fileRefIdOnlyOne
      }
      this.$ajax.post('/tool/uploadImg', postData).then(resp => {
        if (resp.code == 0) {
          this.propShowSuccess && this.utilMessage.success('签名保存成功')
          this.filePath = resp.data
          this.$emit('after-upload', {filePath: this.filePath, base64: base64})
        }
        this.utilVue.loadHide()
      })
    },
    //获取base 64数据
    async getBase64(isMouseleave) {
      if (isMouseleave && this.propAutoSave ) { //如果自动保存
        if (!this.base64Old ||  this.base64.length != this.base64Old.length) { //判断是否有修改
          this.upload(true)
        } else {
          return this.unNeedSave
        }
      }

      if (isMouseleave) {
        return this.unNeedSave
      }

      await this.$refs.esign.generate().then(res => {
        this.base64 = res
      }).catch(err => {
        console.log(err)
      })
      if(this.base64Old && this.base64 == this.base64Old) { //签名未改，无需保存
        this.utilMessage.success('数据保存成功')
        return this.unNeedSave
      }
      return this.base64
    },
    //获取base 64数据
    getData() {
      return this.base64
    },
    //清空签名或者设置签名
    setData(data) {
      if (this.$refs && this.$refs.esign) this.$refs.esign.reset()
      this.base64 = null
    },
    //加载默认签名
    setUserSign() {
      this.setData()
      this.$ajax.get(`/tool/getFilesByRef?fileRefTable=usersign&fileRefId=${utils.getCurrentUser().id}`, {}).then((response) => {
        let data=response.data;
        if (response.code == 0) {
          if(data && data.length >0){
              //1. 获取canvas元素
              var cv = $(this.$refs.esign.$el)[0]
              //2. 获取2D上下文
              var ctx = cv.getContext('2d');
              //3. 新建一个Image对象
              var img = new Image();
              //4. 设置Image的src
              img.src = this.baseApi + data[0].filePath;
              //5. 确定Image加载完毕后将Image画到canvas上
              img.onload = () => {
                ctx.drawImage(img, 0, 0, this.propWidth, this.propHeight);
                this.base64 = cv.toDataURL("image/png")
              }
            }
          }
      }).finally(() => {
      }).catch(() => {
      })
    },
  //设置签名
  setSignPath(filePath) {
    if (this.base64) {
      return
    }
    //1. 获取canvas元素
    var cv = $(this.$refs.esign.$el)[0]
    //2. 获取2D上下文
    var ctx = cv.getContext('2d');
    //3. 新建一个Image对象
    var img = new Image();
    //4. 设置Image的src
    img.src = this.baseApi + filePath;
    //5. 确定Image加载完毕后将Image画到canvas上
    img.onload = () => {
      ctx.drawImage(img, 0, 0, this.propWidth, this.propHeight);
      this.base64 = cv.toDataURL("image/png")
    }
  }
  },
  watch:{
    //禁用状态改变后
    propDisabled:{
      handler(newValue, oldValue) {
        this.isShowOp = !this.propDisabled
      },
      deep: true,
      immediate: true
    }
  }
}
</script>

<style scoped lang="scss">
  .esign-box{
    .esign{
      border: 1px solid darkgreen;
      border-style: dashed;
      margin-left: auto;
      margin-right: auto;
    }

    .btns{
      text-align: center;
      padding-top: 3px;
    }
  }
</style>
